﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeml.Document.Contracts;
using Xeml.Document;
using Mpi.Common.Collections;
using System.Diagnostics;

namespace XemlUtilities.Indexing
{
    public sealed class IndividualIndexer
    {

        #region Singleton pattern
        static readonly IndividualIndexer instance = new IndividualIndexer();

        static IndividualIndexer()
        {
        }

        IndividualIndexer()
        {


        }

        public static IndividualIndexer Instance
        {
            get
            {
                return instance;
            }
        }
        #endregion

        private IDocument doc;

        public void Init(IDocument doc)
        {
            if (this.doc != doc)
            {
                this.doc = doc;
                ResetCache();
            }
        }


        private List<int> _cache = new List<int>();
        public void ResetCache()
        {
            _cache.Clear();
            if (this.doc != null)
            {
                foreach (TreeNode<StoryBase> node in this.doc.StoryBoard)
                {
                    foreach (var item in ((Story)node.Content).Pools)
                    {
                        foreach (var id in item.Individuals)
                        {
                            _cache.Add(id.Id);
                        }
                    }
                }
            }
        }

        public int NextId(bool addToCache)
        {

            Random rand = new Random();
            int nx;
            nx = rand.Next();
            lock (this)
            {

                while (_cache.Contains(nx))
                    nx = rand.Next();

                if (addToCache)
                    _cache.Add(nx);


            }
            return nx;
        }




       
    }
}
